package com.cskaoyan.service.system;

import com.cskaoyan.bean.system.Storage;
import com.cskaoyan.bean.system.StorageExample;
import com.cskaoyan.bo.system.ListWithNameAndKeyBo;
import com.cskaoyan.mapper.StorageMapper;
import com.cskaoyan.vo.system.StorageCreateVo;
import com.cskaoyan.vo.system.StorageListVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    StorageMapper storageMapper;

    // @Value("${pic.fetch-url}")
    // private String picFetchUrl;

    @Override
    public StorageCreateVo storageCreate(StorageCreateVo storageCreateBo) {
        int affectedRows = storageMapper.insertStorage(storageCreateBo);

        StorageCreateVo storageCreateVo = storageMapper.selectStorageById(storageCreateBo.getId());

        // 设置图片的新路径，这样就可以通过mapping映射到绝对路径去访问图片
        // String url = storageCreateVo.getUrl();
        //String newUrl = picFetchUrl + url;
        //storageCreateVo.setUrl(newUrl);

        return storageCreateVo;
    }

    @Override
    public StorageListVo listStorage(ListWithNameAndKeyBo listBo) {
        PageHelper.startPage(listBo.getPage(), listBo.getLimit());

        StorageExample storageExample = new StorageExample();
        storageExample.setOrderByClause(listBo.getSort() + " " + listBo.getOrder());
        StorageExample.Criteria criteria = storageExample.createCriteria();
        if (listBo.getKey() != null && !"".equals(listBo.getKey()))
            criteria.andKeyLike("%" + listBo.getKey() + "%");
        if (listBo.getName() != null && !"".equals(listBo.getName()))
            criteria.andNameLike("%" + listBo.getName() + "%");
        criteria.andDeletedEqualTo(false);

        List<Storage> storageList = storageMapper.selectByExample(storageExample);
        PageInfo<Storage> storagePageInfo = new PageInfo<>(storageList);
        long total = storagePageInfo.getTotal();

        StorageListVo storageListVo = new StorageListVo();
        storageListVo.setItems(storageList);
        storageListVo.setTotal(total);
        return storageListVo;
    }

    @Override
    public Storage updateStorage(Storage storage) {
        storageMapper.updateNameAndTime(storage);
        Storage storageVo = storageMapper.selectByPrimaryKey(storage.getId());
        return storageVo;
    }

    @Override
    public int deleteStorageLogically(Integer id) {
        int affectedRows = storageMapper.deleteByIdLogically(id);
        return affectedRows;
    }
}
